package com.pureut.production.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.*;
import com.pureut.production.domain.dto.FeedRecordDetailsDto;
import com.pureut.production.domain.dto.FeedRecordDto;
import com.pureut.production.domain.dto.FeedRecordMoDto;
import com.pureut.production.domain.dto.FeedingStatisticsDto;
import com.pureut.production.domain.dto.retrospect.MaterialResumeFeedRecordDto;
import com.pureut.production.domain.vo.FeedRecordVo;
import com.pureut.production.domain.vo.FeedRecordmoVo;
import com.pureut.production.mapper.*;
import com.pureut.production.service.DegreasOutputService;
import com.pureut.production.service.IFeedRecordService;
import com.pureut.production.service.SpunlaceOutputService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.vo.FeedVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description 投料记录实现类
 * @Param FeedRecord
 * @Date 23-02-15
 * @Author hl
 **/
@Service
public class FeedRecordServiceImpl extends ServiceImpl<FeedRecordMapper, FeedRecord> implements IFeedRecordService {

    @Resource
    private FeedRecordMapper feedRecordMapper;

    @Resource
    private FeedRecordDetailsMapper feedRecordDetailsMapper;

    @Resource
    private StorageFegin storageFegin;

    @Resource
    private LineStockMapper lineStockMapper;

    /**
     * 水刺产出
     */
    @Resource
    private SpunlaceOutputService spunlaceOutputService;

    /**
     * 脱脂产出mapper
     */
    @Resource
    DegreasOutputMapper degreasOutputMapper;

    /**
     * 脱脂产出service
     */
    @Resource
    @Lazy
    DegreasOutputService degreasOutputService;

    /**
     * 水刺产出
     */
    @Resource
    private SpunlaceOutputMapper spunlaceOutputMapper;

    /**
     * 查询投料记录
     *
     * @param feedRecordVo 投料记录接受类
     * @return list<FeedRecordDto>
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<FeedRecordDto> selectFeedRecordList(FeedRecordVo feedRecordVo) {
        return feedRecordMapper.selectFeedRecordList(feedRecordVo);
    }

    /**
     * 新增投料记录
     *
     * @param feedRecord 投料记录接受类
     * @return 1 成功 0失败
     */
    @Override
    public int insertFeedRecord(FeedRecord feedRecord) {

        List<FeedRecord> feedRecord1 = feedRecordMapper.selectList(new QueryWrapper<FeedRecord>().lambda().eq(FeedRecord::getFeedOrderNumber, feedRecord.getFeedOrderNumber()));

        int save = 1;

        if (feedRecord1.size() == 0) {
            feedRecord.setCreateTime(new Date());
            feedRecord.setDeptId(SecurityUtils.getDeptId());
            feedRecord.setCreateUser(SecurityUtils.getUsername());
            save = feedRecordMapper.insertFeedRecord(feedRecord);
        }

        return save;
    }

    /**
     * 批量新增投料记录
     *
     * @param feedRecordList 投料记录接受类
     * @return 1 成功 0失败
     */
    @Override
    public int insertBatchRecord(List<FeedRecord> feedRecordList) {

        List<FeedRecord> feedRecord1 = feedRecordMapper.selectList(new QueryWrapper<FeedRecord>().lambda().eq(FeedRecord::getFeedOrderNumber, feedRecordList.get(0).getFeedOrderNumber()));

        int save = 1;

        if (feedRecord1.size() == 0) {
            for(FeedRecord entity : feedRecordList){
                entity.setCreateTime(new Date());
                entity.setDeptId(SecurityUtils.getDeptId());
                entity.setCreateUser(SecurityUtils.getUsername());
            }
            save = feedRecordMapper.insertBatchFeedRecord(feedRecordList);
        }

        return save;
    }

    /**
     * 删除投料记录
     *
     * @param feedId 投料记录Id
     * @return 1 成功 0失败
     */
    @Override
    public int deleteFeedRecordById(long feedId) {
        return feedRecordMapper.deleteFeedRecordById(feedId);
    }

    /**
     * 查询投料记录明细
     *
     * @param feedId 投料记录Id
     * @return List<FeedRecordDetailsDto>
     */
    @Override
    public List<FeedRecordDetailsDto> selectFeedRecordDetailsList(long feedId) {
        return feedRecordDetailsMapper.selectFeedRecordDetailsList(feedId);
    }

    /**
     * 新增投料记录明细
     *
     * @param feedRecordDetails 投料记录明细
     * @return 1 成功 0 失败
     */
    @Override
    public int insertFeedRecordDetails(FeedRecordDetails feedRecordDetails) {
        return feedRecordDetailsMapper.insertFeedRecordDetails(feedRecordDetails);
    }

    /**
     * 投料记录统计
     *
     * @param feedId 投料记录id
     * @return List<FeedingStatisticsDto>
     */
    @Override
    public List<FeedingStatisticsDto> selectFeedRecordStatistics(long feedId) {
        return feedRecordMapper.selectFeedRecordStatistics(feedId);
    }


    /**
     * 扫码投料
     *
     * @param feedRecordmoVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FeedRecordMoDto feed(FeedRecordmoVo feedRecordmoVo) {
        //校验当前物料号码是否是生产领料单中的数据
        FeedVo feedVo = new FeedVo();
        feedVo.setMaterialNumber(feedRecordmoVo.getMaterialNumber());
        feedVo.setMoNumber(feedRecordmoVo.getMoNumber());
        AjaxResult ajaxResult = storageFegin.getMoNumber(feedVo);
        if (ajaxResult == null) {
            throw new GlobalException("服务调用失败");
        }
        String code = ajaxResult.get("code").toString();
        //不属于提示入库失败，请确认条码无误后重新扫描
        if (!"200".equals(code)) {
            throw new GlobalException("入库失败，请确认条码无误后重新扫描");
        }
        //通过制令单查出当前物料
        FeedRecordMoDto feedRecordMoDto = new FeedRecordMoDto();

        FeedRecordDto feedRecordDto = feedRecordMapper.viewFeedRecord(feedRecordmoVo.getId());


        LineStock view = lineStockMapper.getView(feedRecordmoVo.getMaterialNumber());

        if (1 == view.getFreezeMark()) {
            throw new GlobalException("此物料已冻结,请重新输入");
        }


        //删除线边库存
        int i = lineStockMapper.deleteByMaterialNumber(feedRecordmoVo.getMaterialNumber());
        //新增投料明细记录
        if (i > 0) {
            FeedRecordDetails feedRecordDetails = new FeedRecordDetails();
            feedRecordDetails.setMaterialNumber(feedRecordmoVo.getMaterialNumber());
            feedRecordDetails.setFeedId(feedRecordDto.getFeedId());
            feedRecordDetails.setFeedOrderNumber(feedRecordDto.getFeedOrderNumber());
            feedRecordDetails.setDetailsBatch(view.getStockBatch());
            feedRecordDetails.setMaterialCode(view.getMaterialCode());
            feedRecordDetails.setGrossWeight(view.getGrossWeight());
            feedRecordDetails.setLineCode(view.getLineCode());
            feedRecordDetails.setMaterialGrade(view.getMaterialGrade());
            feedRecordDetails.setNetWeight(view.getNetWeight());
            feedRecordDetails.setDetailsAlCode(view.getWareAlCode());
            feedRecordDetails.setShift("A");//班次
            feedRecordDetails.setCreateBy(SecurityUtils.getUsername());
            insertFeedRecordDetails(feedRecordDetails);

            //累加投料记录已投重量
            FeedRecord feedRecord = getById(feedRecordmoVo.getId());
            Double investedWeight = feedRecord.getInvestedWeight();
            if (investedWeight == null) {
                investedWeight = 0.0;
            }
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(investedWeight));
            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(view.getNetWeight()));
            BigDecimal add = bigDecimal1.add(bigDecimal2);
            feedRecord.setInvestedWeight(add.doubleValue());

            updateById(feedRecord);
            if ("1".equals(feedRecord.getFeedType())) {
                //水刺产出数量累加，重量累加
                SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, feedRecordmoVo.getMoNumber()));
                Integer feedingNumber = spunlaceOutput.getFeedingNumber();
                if (feedingNumber == null) {
                    feedingNumber = 0;
                }
                spunlaceOutput.setFeedingNumber(feedingNumber + 1);


                Double feedingWeight = spunlaceOutput.getFeedingWeight();
                if (feedingWeight == null) {
                    feedingWeight = 0.0;
                }
                BigDecimal weight1 = new BigDecimal(String.valueOf(feedingWeight));
                BigDecimal weight2 = new BigDecimal(String.valueOf(view.getNetWeight()));
                BigDecimal addWeight = bigDecimal1.add(bigDecimal2);

                spunlaceOutput.setFeedingWeight(addWeight.doubleValue());
                spunlaceOutputService.updateById(spunlaceOutput);
            } else {
                //脱脂产出数量累加，重量累加
                DegreasOutput degreasOutput = degreasOutputMapper.selectOne(new QueryWrapper<DegreasOutput>().lambda().eq(DegreasOutput::getDegreasOrderNumber, feedRecordmoVo.getMoNumber()));
                int quantityFeed = degreasOutput.getQuantityFeed();
                degreasOutput.setQuantityFeed(quantityFeed + 1);


                double quantityFeedWeight = degreasOutput.getQuantityFeedWeight();
                BigDecimal weight1 = new BigDecimal(String.valueOf(quantityFeedWeight));
                BigDecimal weight2 = new BigDecimal(String.valueOf(view.getNetWeight()));
                BigDecimal addWeight = bigDecimal1.add(bigDecimal2);

                degreasOutput.setQuantityFeedWeight(addWeight.doubleValue());
                degreasOutputService.updateById(degreasOutput);
            }

        }


        //提示：
        feedRecordMoDto.setMessage("物料号码：" + feedRecordmoVo.getMaterialNumber() + ",净重：" + view.getNetWeight() + "物料名称：" + feedRecordDto.getMaterialName() + "录入成功");
        feedRecordMoDto.setCode("200");
        return feedRecordMoDto;
    }

    /**
     * 扫码撤销
     *
     * @param feedRecordmoVo
     * @return
     */
    @Override
    public FeedRecordMoDto feedRepeal(FeedRecordmoVo feedRecordmoVo) {
        //查询当前投料中的记录
        FeedRecordDetailsDto feedRecordDetailsDto = feedRecordDetailsMapper.getMaterialNumber(feedRecordmoVo.getMaterialNumber());
        //把数据丢回线边仓
        LineStock lineStock = new LineStock();
        lineStock.setMaterialNumber(feedRecordDetailsDto.getMaterialNumber());
        if (feedRecordDetailsDto.getMaterialGrade() != null) {
            lineStock.setMaterialGrade(feedRecordDetailsDto.getMaterialGrade());//物料等级
        }
        if (feedRecordDetailsDto.getLineCode() != null) {
            lineStock.setLineCode(feedRecordDetailsDto.getLineCode());
        }
        lineStock.setMaterialCode(feedRecordDetailsDto.getMaterialCode());
        lineStock.setStockBatch(feedRecordDetailsDto.getDetailsBatch());
        lineStock.setGrossWeight(feedRecordDetailsDto.getGrossWeight());
        lineStock.setNetWeight(feedRecordDetailsDto.getNetWeight());
        lineStock.setWareAlCode(feedRecordDetailsDto.getDetailsAlCode());
        lineStock.setStockAlCode(feedRecordDetailsDto.getFeedOrderNumber());
        lineStock.setIntoTheTime(new Date());
        int i = lineStockMapper.insertLineStock(lineStock);

        //扣减投料信息
        FeedRecord feedRecord = feedRecordMapper.selectOne(new QueryWrapper<FeedRecord>().lambda().eq(FeedRecord::getFeedOrderNumber, feedRecordDetailsDto.getFeedOrderNumber()));

        //当前投料重量
        double investedWeight = feedRecord.getInvestedWeight();
        BigDecimal investedWeightBigDecimal = new BigDecimal(String.valueOf(investedWeight));

        BigDecimal feedBigDecimal = new BigDecimal(String.valueOf(feedRecordDetailsDto.getNetWeight()));

        BigDecimal subtract = investedWeightBigDecimal.subtract(feedBigDecimal);

        feedRecord.setInvestedWeight(Double.parseDouble(subtract.toString()));

        //修改投料重量（扣除）
        feedRecordMapper.updateById(feedRecord);

        //如果是水刺撤销投料
        if ("1".equals(feedRecord.getFeedType())) {
            //扣除水刺产出重量
            SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, feedRecordDetailsDto.getFeedOrderNumber()));
            //水刺投料数量
            Integer feedingNumber = spunlaceOutput.getFeedingNumber();
            if (feedingNumber == null) {
                feedingNumber = 0;
            }
            spunlaceOutput.setFeedingNumber(feedingNumber - 1);
            spunlaceOutput.setFeedingWeight(Double.parseDouble(subtract.toString()));
            spunlaceOutputService.updateById(spunlaceOutput);

        } else {
            //扣除脱脂产出重量
            DegreasOutput degreasOutput = degreasOutputMapper.selectOne(new QueryWrapper<DegreasOutput>().lambda().eq(DegreasOutput::getDegreasOrderNumber, feedRecordDetailsDto.getFeedOrderNumber()));
            //脱脂投料数量
            int quantityFeed = degreasOutput.getQuantityFeed();
            if (quantityFeed != 0) {
                degreasOutput.setQuantityFeed(quantityFeed - 1);
            }
            degreasOutput.setQuantityFeedWeight(Double.parseDouble(subtract.toString()));
            degreasOutputService.updateById(degreasOutput);
        }

        //删除投料记录
        if (i > 0) {
            feedRecordDetailsMapper.deleteByMaterialNumber(feedRecordmoVo.getMaterialNumber());
        }
        FeedRecordMoDto feedRecordMoDto = new FeedRecordMoDto();
        feedRecordMoDto.setMessage("物料号码：" + feedRecordmoVo.getMaterialNumber() + ",净重：" + feedRecordDetailsDto.getNetWeight() + "物料名称：" + feedRecordDetailsDto.getMaterialName() + "撤销成功");
        feedRecordMoDto.setCode("200");
        return feedRecordMoDto;
    }

    /**
     * 获取投料记录
     *
     * @param moNumber
     * @return
     */
    @Override
    public boolean getInfo(String moNumber) {

        List<FeedRecord> feedRecord = feedRecordDetailsMapper.getInfo(moNumber);

        return feedRecord.size() > 0;
    }

    /**
     * 通过物料号码查询投料记录明细
     *
     * @param materialNumber
     * @return
     */
    @Override
    public MaterialResumeFeedRecordDto getMaterialNumberInfo(String materialNumber) {
        return feedRecordDetailsMapper.getMaterialNumberInfo(materialNumber);
    }


}
